/*
 * Copyright (C) 2009-2018 Hangzhou 2Dfire Technology Co., Ltd. All rights reserved
 */
package com.ws.soa.consumer.service;

import com.google.common.base.Preconditions;
import com.ws.soa.consumer.dao.mapper.WorksCommentMapper;
import com.ws.soa.consumer.domain.WorksCommentDO;
import com.ws.soa.consumer.dto.WorkCommentDTO;
import com.ws.soa.consumer.util.UUIDUtil;
import com.ws.soa.consumer.vo.WorkCommentVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * WorksCommentService
 *
 * @author luobosi@2dfire.com
 * @since 2019-03-06
 */
@Service
public class WorksCommentService {

    @Resource
    private WorksCommentMapper worksCommentMapper;

    @Resource
    private WorksService worksService;

    public boolean save(String memberId, String nickName, WorkCommentDTO workCommentDTO) {
        Preconditions.checkArgument(StringUtils.isNoneEmpty(memberId));
        Preconditions.checkArgument(StringUtils.isNoneEmpty(nickName));
        Preconditions.checkArgument(null != workCommentDTO);

        this.worksService.increaseCommentNum(workCommentDTO.getWorkId());

        return this.worksCommentMapper.insert(this.dtoToDO(memberId, nickName, workCommentDTO)) > 0;
    }

    public WorkCommentVO findAllByWorkId(String workId) {
        List<WorksCommentDO> workCommentDOList = this.worksCommentMapper.findAllByWorkId(workId);
        return this.packageWorkCommentVO(workCommentDOList, workId);
    }

    public List<WorksCommentDO> findAll() {
        return this.worksCommentMapper.findAll();
    }

    private WorksCommentDO dtoToDO(String memberId, String nickName, WorkCommentDTO workCommentDTO) {
        WorksCommentDO worksCommentDO = new WorksCommentDO();

        worksCommentDO.setId(UUIDUtil.getUUID());
        worksCommentDO.setUserId(memberId);
        worksCommentDO.setWorkId(workCommentDTO.getWorkId());
        worksCommentDO.setContent(workCommentDTO.getContent());
        worksCommentDO.setUsername(nickName);
        worksCommentDO.setCommentType(workCommentDTO.getCommentType());

        return worksCommentDO;
    }

    private WorkCommentVO packageWorkCommentVO(List<WorksCommentDO> workCommentDOList, String workId) {

        List<String> commentList = new ArrayList<>();
        WorkCommentVO workCommentVO = new WorkCommentVO();
        workCommentVO.setWorkId(workId);
        workCommentVO.setCommentList(commentList);

        workCommentDOList.forEach(worksCommentDO -> commentList.add(worksCommentDO.getContent()));

        return workCommentVO;
    }
}
